<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');



require_once(APPPATH .'/libraries/REST_Controller.php');



/**
 * class File
 * Will be the controller for all file actions within the vta application.
 *
 * @author      Jeroen Sen <jeroensen@22vision.nl>
 * @version     20120925
 *
 */
class File extends REST_Controller {



    /**
     * public function upload_post
     *
     *
     * @author        Jeroen Sen <jeroensen@22vision.nl>
     * @version       20120925
     * @param         void
     * @return        void
     *
     */
    public function imageupload_post()
    {
error_log(__METHOD__);

        $files = $_FILES['photos'];
        $uploadRoot = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR;

        $return = array();
        $return['result'] = false;


        if (isset($files['name'])) {

            foreach ($files['name'] as $i => $data) {

                $error = $files['error'][$i];

                if ($error == UPLOAD_ERR_OK) {

                    $targetPath = $uploadRoot . basename($files["name"][$i]);
                    $uploadedFile = $files["tmp_name"][$i];

                    if (is_uploaded_file($uploadedFile)) {
                        if (!move_uploaded_file($uploadedFile, $targetPath)) {
                            echo "Error moving uploaded file";
                        } else {

                            $imageData = explode(DIRECTORY_SEPARATOR, $targetPath);

                            $imageName = array_pop($imageData);
                            $imageLocation = implode(DIRECTORY_SEPARATOR, $imageData);

                            // try to retrieve the image based on the filename and filelocation
                            $criteria = array('filename' => $imageName, 'filelocation' => $imageLocation);
                            $orderBy = array('id' => 'ASC');

                            $images = $this->doctrine->em->getRepository('Entities\Image')->findBy($criteria, $orderBy);

                            if (isset($images) && is_array($images) && count($images) > 0) {

                                // due to database constraints there can only be one image, so break free! :)
                                foreach ($images as $index => $image) {
                                    break;
                                }

                            } else {

                                // the image was succesfully uploaded, create a new object and store it, also retrieve the image coords when possible
                                $image = new Entities\Image;

                                $image->setFilename($imageName);
                                $image->setFilelocation($imageLocation);

                                $this->doctrine->em->persist($image);
                                $this->doctrine->em->flush();

                            }

                            $coords = $image->getGpsData();
                            $address = $image->getAddress($coords['latitude'], $coords['longitude']);
                            $dimensions = $image->getDimensions();

                            $config['image_library'] = 'gd2';
                            $config['source_image'] = $targetPath;
                            $config['create_thumb'] = TRUE;
                            $config['maintain_ratio'] = TRUE;
                            $config['width'] = 100;
                            $config['height'] = 100;

                            $this->load->library('image_lib', $config);

                            if ($this->image_lib->resize() == true) {
                                $thumbnail = DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR . $image->getThumbnailFilename();
                            }



                            $return['data']['coords'] = $coords;
                            $return['data']['address'] = $address;
                            $return['data']['dimensions'] = $dimensions;
                            $return['data']['thumbnail'] = $thumbnail;
                            $return['data']['original'] = DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR . $image->getFilename();
                            $return['result'] = true;

                        }
                    }

                } else {
                    // See http://php.net/manual/en/features.file-upload.errors.php
                    echo "Error code " . $error;
                }

            } // foreach ($files as $i => $data)

        } //if (isset($files['name']))

error_log(print_r($return, true));

        $this->response($return);

    } // public function upload_post()





} // class File extends REST_Controller